package com.huanqiu.mylib.util;

import android.content.Context;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class IOUtil {

    /**
     * 保存为临时文件
     *
     * @return 临时文件路径
     */
    @Nullable
    public static String saveTempFile(@NonNull Context context, @NonNull byte[] data, @Nullable String prefix) {
        prefix = TextUtils.isEmpty(prefix) ? "tmp" : prefix;

        File file = new File(context.getCacheDir(), prefix + "-" + System.currentTimeMillis());
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            fos.write(data);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            IOUtils.closeQuietly(fos);
        }

        return file.getAbsolutePath();
    }

}
